package com.example.park2301.register

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.park2301.R
import com.example.park2301.databinding.ActivityRegisterBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

@Route(path = "/app/RegisterActivity")
@AndroidEntryPoint
class RegisterActivity : BaseActivity<ActivityRegisterBinding,RegisterViewModel>() {

    override fun initView() {
        binding.registerCodeBtn.setOnClickListener {
            if (!RegexUtils.isMobileSimple(binding.registerPhone.text.toString())){
                ToastUtils.showLong("请输入正确的手机号")
                return@setOnClickListener
            }else{
                //随机数验证码
                val code = Random.nextInt(1000, 9999)
                ToastUtils.showLong("验证码为：$code")
            }
            lifecycleScope.launch {
                for (i in 10 downTo 1){
                    delay(1000)
                    binding.registerCodeBtn.text = "$i 秒重新获取"
                    binding.registerCodeBtn.isEnabled =false
                    if (i==1){
                        binding.registerCodeBtn.text = "获取验证码"
                        binding.registerCodeBtn.isEnabled =true
                    }
                }
            }
        }

        binding.btnRegister.setOnClickListener {
            if (binding.registerPassword.text.toString() .isEmpty()||binding.registerNewPassword.text.toString().isEmpty()){
                ToastUtils.showLong("请输入密码")
                return@setOnClickListener
            }else if (binding.registerPassword.text.toString() != binding.registerNewPassword.text.toString()){
                ToastUtils.showLong("密码不一致")
                return@setOnClickListener
            }else {
                vm.register(binding.registerPhone.text.toString(),binding.registerPassword.text.toString())
            }
        }


    }

    override fun initData() {
        vm.registerData.observe(this){
            Log.i("xhl",it.toString())
            ARouter.getInstance().build("/app/UserActivity").navigation()
        }
    }
}